package com.weavernorth.sysap.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weavernorth.sysap.bean.*;
import com.weavernorth.sysap.dao.SyncOrgStrucDao;
import com.weavernorth.sysap.dao.SyncOrgStrucDaoImpl;
import com.weavernorth.sysap.util.*;
import com.weavernorth.util.Logger4jUtil;
import ln.LN;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.matrix.MatrixUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 同步组织结构（集团、分部、部门、岗位、人员）实现类
 *
 * @author Zm
 * @version v1.0 created by 2019-10-09
 */
public class SyncOrgStrucServiceImpl extends SyncUtil implements SyncOrgStrucService {
//    public static Log log = LogFactory.getLog(SyncOrgStrucServiceImpl.class.getName());
//    private Logger log = new Logger4jUtil().getLogger("/Timmer/synchronization_log/");
    /**
     * 请求组织信息
     */
    @Override
    public void syncOrgInfo(Logger log,String isall) {

        //工具类
        SyncUtil syncUtil = new SyncUtil();
        //获取同步分部接口的url
        String strSyncOrgInfoUrl = Util.null2String(this.getPropValue("sapMess", "syncorginfourl"));
        log.info("同步组织的接口url==" + strSyncOrgInfoUrl);
        //查询分部部门hr请求xml
        String strRequestXml = syncUtil.getOrgXml(log,"org", null, isall);
        log.info("同步组织的xml:" + strRequestXml);
        //******1.获取要同步的分部数据
        JSONObject jsonOrg = this.splitSubcompanyAndDepartmentData(log,this.getSyncDataInfos(log,strSyncOrgInfoUrl, strRequestXml), CommonConstant.ORG_TYPE_SUBCOMPANY);
        //**2.分部和部门在SAP是同一个接口,则调用一次区分开数据
        //同步分部数据
        JSONArray jsonSubcom = JSON.parseArray(JSONObject.toJSONString(jsonOrg.get("subcompany")));
        List<JSONObject> listSubcom = syncSubcompanyInfo(log,jsonSubcom);
        log.info("同步分部返回数据" + listSubcom.toString());
        //同步部门
        JSONArray jsonDepartment = JSON.parseArray(JSONObject.toJSONString(jsonOrg.get("department")));
        List<JSONObject> listDepart = syncDepartmentInfo(log,jsonDepartment);
        log.info("同步部门返回数据" + listDepart.toString());
        listSubcom.addAll(listDepart);
        //  log.info("回调数据" + listSubcom.toString());
        //**3.把分部和部门返回的回写数据,组成一个list返回给SAP,因为分部和部门在一个接口里
        this.writeBackSyncInfo(log,CommonConstant.SYNC_TYPE_ORG, listSubcom, isall);
    }


    /**
     * 同步分部信息
     */

    public List<JSONObject> syncSubcompanyInfo(Logger log,JSONArray subCompanyList) {

        //同步日志记录
//        SyncLog syncLog = new SyncLog();
        HrmSubCompany hrmSubCompany = new HrmSubCompany();
        SyncOrgStrucDao sosDao = new SyncOrgStrucDaoImpl();
        SubCompanyComInfo scci = new SubCompanyComInfo();
        //回写数据list集合
        List<JSONObject> writeBackDataList = new ArrayList<JSONObject>();
        //工具类
        SyncUtil syncUtil = new SyncUtil();
        //******1.存在分部数据，则进行同步
        if (subCompanyList != null) {
            //******2.遍历分部数据，逐条插入或更新到OA数据库
            for (int index = 0; index < subCompanyList.size(); index++) {
                //回写数据json
                JSONObject writeBackDataJson = new JSONObject();
                //******3.1获取要同步的参数
                JSONObject subComJson = JSON.parseObject(String.valueOf(subCompanyList.get(index)));
                //组织编码
                String strCompanyCode = Util.null2String(subComJson.get("objid"));
                //组织名称全称
                String strSubCompanyName = Util.null2String(subComJson.get("stext"));
                //组织名称简称
                String strSubCompanyShortName = Util.null2String(subComJson.get("stext"));
                //顺序 X代表不更新此字段,如果是数字就更新即可
                String strSort = Util.null2String(subComJson.get("sort"));
                //组织状态 Y启用/N禁用
                String strStype = Util.null2String(subComJson.get("stype"));
                //上级组织编码
                String strParentCompanyCode = Util.null2String(subComJson.get("objid_sj"));
                //所属分部
                String strBelongCompanyCode = Util.null2String(subComJson.get("objid_fb"));
                //同步的数据打印出来，方便查看错误原因
                log.info("SAP传入的分部信息{组织名称全称stext:" + strSubCompanyName + ",组织名称简称stext:" + strSubCompanyShortName +
                        ",组织编码objid:" + strCompanyCode + ",上级组织编码objid_sj:" + strParentCompanyCode +
                        ",组织状态stype:" + strStype + ",顺序sort:" + strSort+",所属分部objid_fb："+strBelongCompanyCode+"}");

                //同步日志数据初始化
//                syncLog.setSyncType(CommonConstant.SYNC_TYPE_ORG);
//                syncLog.setSyncDate(CommonToSapUtil.getCurDate());
//                syncLog.setSyncTime(CommonToSapUtil.getCurTime());
//                syncLog.setSyncCode(strCompanyCode);
//                syncLog.setSyncName(strSubCompanyName);
                //回写数据
                writeBackDataJson.put("objid", strCompanyCode);

                //******3.2判断一些必须字段是否有值，来决定是否可同步该条记录
                //判断分部编码是否存在
                if ("".equals(strCompanyCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "分部编号为空");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("分部编号为空");
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("分部编号为空");
//                    //日志插入
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }
                //如果组织编码不为空,则查询部门表里是否存在此编码数据,用于部门变分部的处理,部门需封存
                else {
                    sosDao.dealDepartment(strCompanyCode);
                }
                //判断部门名称是否为空
                if ("".equals(strSubCompanyName)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "分部名称为空");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("分部名称为空");
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("分部名称为空");
                    //日志插入
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }
                //如果上级编码为空,则返回失败
                if ("".equals(strParentCompanyCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "上级分部编码为空");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("上级分部编码为空");
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("上级分部编码为空");
                    //日志插入
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }
                //如果所属分部编码为空,则返回失败
                if ("".equals(strBelongCompanyCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "所属分部编码编码为空");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("所属分部编码编码为空");
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("所属分部编码为空");
//                    //日志插入
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }

                //存储要插入或更新的数据到分部实体类的对象中
                hrmSubCompany.setSubCompanyCode(strCompanyCode);
                hrmSubCompany.setSubCompanyName(strSubCompanyName);
                hrmSubCompany.setSubCompanyDesc(strSubCompanyShortName);
                //X代表不更新此字段,如果是数字就更新即可
                hrmSubCompany.setShowOrder(strSort);
                //是否封存该分部,传过来的数是N则代表封存,OA中标识为1；反之亦然。
                if ("N".equals(strStype)) {
                    hrmSubCompany.setCanceled(CommonConstant.CANCELED);
                } else {
                    hrmSubCompany.setCanceled(CommonConstant.NOT_CANCELED);
                }

                //查找该分部的上级分部是否存在。确认上级编码无上级时是否为空
                if (!"".equals(strParentCompanyCode)) {
                    //查找上级分部id
                    String strSupSubId = sosDao.getIdByCode("hrmsubcompany", strParentCompanyCode);
                    log.info("根据sap的objid_sj："+strParentCompanyCode+"查找上级分部id的Sql:select * from hrmsubcompany where subcompanycode='"+strParentCompanyCode+"'");
                    log.info("上级分部id:"+strSupSubId);
                    if ("".equals(strSupSubId)) {
                        hrmSubCompany.setSupSubComId(0);
                    } else {
                        hrmSubCompany.setSupSubComId(Integer.parseInt(strSupSubId));
                    }

                } else {
                    hrmSubCompany.setSupSubComId(0);
                }
                //******4.数据的插入或更新开始执行
                //根据分部编码获取分部id，分部id为空字符串则执行插入操作；分部id有值的话，则执行更新操作。
                String strSubIdStr = sosDao.getIdByCode("hrmsubcompany", strCompanyCode);
                log.info("根据SAP的分部编码："+strCompanyCode+"查找oa分部id的sql: select * from hrmsubcompany where subcompanycode='"+strCompanyCode+"'");
                log.info("根据SAP编码返回的分部id" + strSubIdStr);
                //获取控股集团组织编码,此分部不需同步
                String strGroupCode = Util.null2String(this.getPropValue("sapMess", "groupcode"));
                log.info("当前不需同步组织编码:" + strGroupCode + ",当前编码:" + strGroupCode);
                if (!strCompanyCode.equals(strGroupCode)) {
                    if ("".equals(strSubIdStr)) {
                        log.info("分部id为空，插入分部信息！");
                        boolean insertSubComStatus = sosDao.insertHrmSubCompany(hrmSubCompany);
                        if (!insertSubComStatus) {
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                            writeBackDataJson.put("ifmsg", "分部编码" + hrmSubCompany.getSubCompanyCode() + "同步失败");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                            syncLog.setSyncInfoDesc("分部编码为" + hrmSubCompany.getSubCompanyCode() + ",插入分部数据的时候，插入失败.");
                            log.info("分部编码" + hrmSubCompany.getSubCompanyCode() + "同步失败");
                        } else {
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                            writeBackDataJson.put("ifmsg", "分部编码" + hrmSubCompany.getSubCompanyCode() + "同步成功");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                            syncLog.setSyncInfoDesc("分部同步成功");
                            log.info("分部编码" + hrmSubCompany.getSubCompanyCode() + "同步成功");
                        }
                    } else {

                        hrmSubCompany.setId(strSubIdStr);
                        boolean updateSubComStatus = sosDao.updateHrmSubCompany(hrmSubCompany);
                        if (!updateSubComStatus) {
                            log.error("分部编码为" + hrmSubCompany.getSubCompanyCode() + ",更新分部数据的时候，更新失败.");
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                            writeBackDataJson.put("ifmsg", "分部编码" + hrmSubCompany.getSubCompanyCode() + "同步成功");

//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                            syncLog.setSyncInfoDesc("分部编码为" + hrmSubCompany.getSubCompanyCode() + ",更新分部数据的时候，更新失败.");
                        } else {
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                            writeBackDataJson.put("ifmsg", "分部编码" + hrmSubCompany.getSubCompanyCode() + "同步成功");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                            syncLog.setSyncInfoDesc("分部同步成功");
                            log.info("分部编码" + hrmSubCompany.getSubCompanyCode() + "同步成功");
                        }
                    }
                    //回写数据
                    writeBackDataList.add(writeBackDataJson);
//                    sosDao.insertSyncLog(syncLog);
                }

            }

            //日志插入完成后,开启线程授权
            //传入授权类的sql
            //模块id
            log.info("开始授权--");
            int modeId = SyncOrgStrucDaoImpl.getModeIdByTableName("uf_sjtbrz");
            log.info("模块id:"+modeId);
            String  sql="select id from uf_sjtbrz where syncdate='"+CommonToSapUtil.getCurDate()+"' and synctype='"+CommonConstant.SYNC_TYPE_ORG+"'";
            log.info("授权sql:"+sql);
            ModeDataShareByThreads modeDataShareByThread = new ModeDataShareByThreads();
            modeDataShareByThread.setModeid(modeId);
            modeDataShareByThread.setSql(sql);
            new Thread(modeDataShareByThread).start();
            log.info("结束授权--");

            //矩阵同步
            MatrixUtil.sysSubcompayData();

        } else {
            log.info("分部同步==>syncSubcompanyInfo():本次没有可同步的分部数据。");
        }


        //分部清楚缓存
        syncUtil.clearCache(0);
//        scci.removeCompanyCache();

        return writeBackDataList;
    }

    /**
     * 同步部门信息
     */

    public List<JSONObject> syncDepartmentInfo(Logger log,JSONArray departmentList) {
        //同步日志记录
//        SyncLog syncLog;
        HrmDepartment hrmDepartment = new HrmDepartment();
        SyncOrgStrucDao sosDao = new SyncOrgStrucDaoImpl();
//        DepartmentComInfo dci = new DepartmentComInfo();
        JSONObject subComMap;
        //同步工具类
        SyncUtil syncUtil = new SyncUtil();
        //回写数据list集合
        List<JSONObject> writeBackDataList = new ArrayList<JSONObject>();
        //******1.存在部门数据，则进行同步
        if (departmentList != null) {
            //******2.遍历部门数据，逐条插入或更新到OA数据库
            for (int index = 0; index < departmentList.size(); index++) {
                //回写数据json
                JSONObject writeBackDataJson = new JSONObject();
//                syncLog = new SyncLog();
                //******2.1获取要同步的参数
                subComMap = JSON.parseObject(String.valueOf(departmentList.get(index)));
                //部门名
                String strDepartmentName = Util.null2String(subComMap.get("stext"));
                log.info("部门名stext："+strDepartmentName);
                //部门全称
                String strDepartmentMark = Util.null2String(subComMap.get("stext"));
                log.info("部门全称stext："+strDepartmentMark);
                //部门编码
                String strDepartmentCode = Util.null2String(subComMap.get("objid"));
                log.info("部门编码objid："+strDepartmentCode);

                //上级部门编码
                String strDepartmentParentCode = Util.null2String(subComMap.get("objid_sj"));
                log.info("上级部门编码objid_sj："+strDepartmentParentCode);
                //是否封存  Y启用/N禁用
                String strCanceled = Util.null2String(subComMap.get("stype"));
                log.info("是否封存stype："+strCanceled);
                //排序
                String strShowOrder = Util.null2String(subComMap.get("sort"));
                log.info("排序sort："+strShowOrder);
                //部门所属分部code
                String strSubCompanyCode = Util.null2String(subComMap.get("objid_fb"));
                log.info("部门所属分部objid_fb："+strSubCompanyCode);

                //同步日志数据初始化
//                syncLog.setSyncType(CommonConstant.SYNC_TYPE_ORG);
//                syncLog.setSyncDate(CommonToSapUtil.getCurDate());
//                syncLog.setSyncTime(CommonToSapUtil.getCurTime());
//                syncLog.setSyncCode(strDepartmentCode);
//                syncLog.setSyncName(strDepartmentName);
                writeBackDataJson.put("objid", strDepartmentCode);

                //******2.2判断一些必须字段是否有值，来决定是否可同步该条记录
                //判断部门编码是否为空
                if ("".equals(strDepartmentCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "部门编号不能为空");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("部门编号不能为空，同步失败");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("部门编号为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }//如果组织编码不为空,则查询部门表里是否存在此编码数据,用于部门变分部的处理,部门需封存
                else {
                    sosDao.dealSubcompany(strDepartmentCode);
                }
                // 判断部门名称是否为空
                if ("".equals(strDepartmentName)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "部门名称不能为空");
                    writeBackDataList.add(writeBackDataJson);

                    log.info("部门名称不能为空，同步失败");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("部门名称为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }
                //所属分部不存在的，不做任何操作
                if ("".equals(strSubCompanyCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "部门所属分部不能为空");
                    writeBackDataList.add(writeBackDataJson);

                    log.info("部门所属分部不能为空，同步失败");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("部门所属分部为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;

                }
                //存储要插入或更新的数据到部门实体类的对象中
                hrmDepartment.setDepartmentCode(strDepartmentCode);
                hrmDepartment.setDepartmentMark(strDepartmentMark);
                hrmDepartment.setDepartmentName(strDepartmentName);
                hrmDepartment.setShowOrder(strShowOrder);
                //是否封存该分部,传过来的数是N则代表封存,OA中标识为1；反之亦然。
                if ("N".equals(strCanceled)) {
                    hrmDepartment.setCanceled(CommonConstant.CANCELED);
                } else {
                    hrmDepartment.setCanceled(CommonConstant.NOT_CANCELED);
                }

                //查找该部门的上级部门是否存在。
                if (!strDepartmentParentCode.equals("")) {
                    String strSupSubId = sosDao.getIdByCode("hrmdepartment", strDepartmentParentCode);
                    if (strSupSubId.equals("")) {
                        hrmDepartment.setSupDepId(0);
                    } else {
                        hrmDepartment.setSupDepId(Integer.parseInt(strSupSubId));
                    }
                } else {
                    hrmDepartment.setSupDepId(0);
                }

                //查找该部门对应的分部的id
                if (strSubCompanyCode.equals("")) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "分部code为空");
                    writeBackDataList.add(writeBackDataJson);

                    log.info("部门code为：" + hrmDepartment.getDepartmentCode() + "的数据对应的分部code为空，无法同步该部门。");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("分部code为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                } else {
                    String strSubComId = sosDao.getIdByCode("hrmsubcompany", strSubCompanyCode);
                    if (strSubComId.equals("")) {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                        writeBackDataJson.put("ifmsg", "部门同步时，部门code为：" + hrmDepartment.getDepartmentCode() + "分部code为：" + strSubCompanyCode + "的数据，查询不到对应的分部记录，无法同步该部门");
                        writeBackDataList.add(writeBackDataJson);

                        log.info("部门同步时，部门code为：" + hrmDepartment.getDepartmentCode() + "分部code为：" +
                                strSubCompanyCode + "的数据，查询不到对应的分部记录，无法同步该部门。");

                        //日志插入
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("部门code为：" + hrmDepartment.getDepartmentCode() + "分部code为：" +
//                                strSubCompanyCode + "的数据，查询不到对应的分部记录");
//                        sosDao.insertSyncLog(syncLog);
                        continue;
                    } else {
                        hrmDepartment.setSubCompanyId(Integer.parseInt(strSubComId));
                    }
                }
                //******3.数据的插入或更新开始执行
                //根据部门编码获取部门id，部门id为空字符串则执行插入操作；部门id有值的话，则执行更新操作。
                String strDepId = sosDao.getIdByCode("hrmdepartment", strDepartmentCode);
                log.info("编码查出部门id" + strDepId);
                if (strDepId.equals("")) {
                    boolean insertDepStatus = sosDao.insertHrmDepartment(hrmDepartment);
                    if (!insertDepStatus) {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                        writeBackDataJson.put("ifmsg", "部门编码为" + hrmDepartment.getDepartmentCode() + "插入的时候，插入失败.");
                        log.error("部门编码为" + hrmDepartment.getDepartmentCode() + "插入的时候，插入失败.");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("部门编码为" + hrmDepartment.getDepartmentCode() + "插入的时候，插入失败.");
                    } else {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                        writeBackDataJson.put("ifmsg", "部门编码为" + hrmDepartment.getDepartmentCode() + "同步成功");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("部门同步成功");
                        log.info("部门同步成功");
                    }

                } else {
                    hrmDepartment.setId(strDepId);
                    boolean updateDepStatus = sosDao.updateHrmDepartment(hrmDepartment);
                    if (!updateDepStatus) {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                        writeBackDataJson.put("ifmsg", "部门编码为" + hrmDepartment.getDepartmentCode() + "更新部门数据失败");
                        log.error("部门编码为" + hrmDepartment.getDepartmentCode() + ",更新部门数据失败.");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("部门编码为" + hrmDepartment.getDepartmentCode() + ",更新部门数据失败.");
                    } else {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                        writeBackDataJson.put("ifmsg", "部门编码为" + hrmDepartment.getDepartmentCode() + "同步成功");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("部门同步成功");
                        log.info("部门同步成功");
                    }
                }
                //回写数据
                writeBackDataList.add(writeBackDataJson);
                //日志插入
//                sosDao.insertSyncLog(syncLog);

            }

            //日志插入完成后,开启线程授权
            //传入授权类的sql
            //模块id
            log.info("开始授权--");
            int modeId = SyncOrgStrucDaoImpl.getModeIdByTableName("uf_sjtbrz");
            log.info("模块id:"+modeId);
            String  sql="select id from uf_sjtbrz where syncdate='"+CommonToSapUtil.getCurDate()+"' and synctype='"+CommonConstant.SYNC_TYPE_ORG+"'";
            log.info("授权sql:"+sql);
            ModeDataShareByThreads modeDataShareByThread = new ModeDataShareByThreads();
            modeDataShareByThread.setModeid(modeId);
            modeDataShareByThread.setSql(sql);
            new Thread(modeDataShareByThread).start();
            log.info("结束授权--");



            //矩阵同步
            MatrixUtil.sysDepartmentData();

        } else {
            log.info("部门同步==>syncDepartmentInfo():本次没有可同步的部门数据。");
        }

        // 部门缓存清除类
        syncUtil.clearCache(1);

        return writeBackDataList;

    }


    /**
     * 同步岗位信息
     */
    @Override
    public void syncJobtitlesInfo(Logger log,String isall) {
        log.info("开始同步岗位信息---");
        //同步日志记录
//        SyncLog syncLog = new SyncLog();
        HrmJobtitles hrmJobtitles = new HrmJobtitles();
        SyncOrgStrucDao sosDao = new SyncOrgStrucDaoImpl();
        JobTitlesComInfo jtc = new JobTitlesComInfo();
        //同步工具类
        SyncUtil syncUtil = new SyncUtil();
        //获取同步岗位路径
        String strSyncJobtitlesInfoUrl = Util.null2String(this.getPropValue("sapMess", "syncJobtitleUrl"));
        log.info("同步岗位地址" + strSyncJobtitlesInfoUrl);
        //查询岗位xml
        String strRequestXml = syncUtil.getOrgXml(log,"jobtitles", null, isall);
        log.info("岗位的xml:" + strRequestXml);
        // log.info("同步的xml:"+strRequestXml);
        //******1.获取要同步的岗位数据
        JSONArray jobtitlesList = this.getSyncDataInfos(log,strSyncJobtitlesInfoUrl, strRequestXml);
        //******2.存在岗位数据，则进行同步
        if (jobtitlesList != null) {
            //回写数据list集合
            List<JSONObject> writeBackDataList = new ArrayList<JSONObject>();
            //******3.遍历岗位数据，逐条插入或更新到OA数据库
            for (int index = 0; index < jobtitlesList.size(); index++) {
                //回写数据json
                JSONObject writeBackDataJson = new JSONObject();
                //******3.1获取要同步的参数
                JSONObject subComMap = JSON.parseObject(jobtitlesList.get(index).toString());
                //岗位名
                String strJobtitlesName = Util.null2String(subComMap.get("stext"));
                //岗位全称
                String strJobtitlesMark = Util.null2String(subComMap.get("stext"));
                //组织编码(分部或部门)
                String strJobtitlesDepartCode = Util.null2String(subComMap.get("objid"));
                //岗位编码
                String strJobtitlesCode = Util.null2String(subComMap.get("objid_gw"));
                //岗位序列
                String strGwxl = Util.null2String(subComMap.get("zngwxl"));
                //岗位状态 0禁用  1启用
                String strJobtitlesStatus = Util.null2String(subComMap.get("gwzt"));

                //同步的数据打印出来，方便查看错误原因
                String job_data_log="strJobtitlesCode:" + strJobtitlesCode + ",strJobtitlesName:" + strJobtitlesName +
                        ",strJobtitlesMark:" + strJobtitlesMark + ",strJobtitlesDepartCode:" + strJobtitlesDepartCode + ",strJobtitlesStatus:" + strJobtitlesStatus+",zngwxl:"+strGwxl;
                log.info("岗位同步数据获取："+job_data_log);
                //同步日志数据初始化
//                syncLog.setSyncType(CommonConstant.SYNC_TYPE_JOB);
//                syncLog.setSyncDate(CommonToSapUtil.getCurDate());
//                syncLog.setSyncTime(CommonToSapUtil.getCurTime());
//                syncLog.setSyncCode(strJobtitlesCode);
//                syncLog.setSyncName(strJobtitlesName);
                //回调数据
                writeBackDataJson.put("id", strJobtitlesCode);
                //******3.2判断一些必须字段是否有值，来决定是否可同步该条记录
                //判断岗位编码是否为空
                if ("".equals(strJobtitlesCode)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "岗位编号不能为空，同步失败");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("岗位编号不能为空，同步失败");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("岗位编号为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;
                }
                // 判断岗位名称是否为空
                if ("".equals(strJobtitlesName)) {
                    //回写数据
                    writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                    writeBackDataJson.put("ifmsg", "岗位名称不能为空，同步失败");
                    writeBackDataList.add(writeBackDataJson);
                    log.info("岗位名称不能为空，同步失败");
                    //日志插入
//                    syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                    syncLog.setSyncInfoDesc("岗位名称为空");
//                    sosDao.insertSyncLog(syncLog);
                    continue;

                }
                //获取部门id
                String departId = sosDao.getIdByCode("hrmdepartment", strJobtitlesDepartCode);
                //1.部门id为空的话,则从分部表里查询,查询到则直接建相同数据至部门表
                if ("".equals(departId)) {
                    sosDao.insertDepartFromSubcompany(strJobtitlesDepartCode);
                    //2.插入完成后,查询当前部门id,插入的有"_"
                    departId = sosDao.getIdByCode("hrmdepartment", "_" + strJobtitlesDepartCode);
                    strJobtitlesDepartCode="_"+strJobtitlesDepartCode;
                }

                //存储要插入或更新的数据到岗位实体类的对象中
                //岗位编码
                hrmJobtitles.setJobtitleCode(strJobtitlesCode);
                //岗位名称
                hrmJobtitles.setJobtitleName(strJobtitlesName);
                //岗位标识
                hrmJobtitles.setJobtitleMark(strJobtitlesMark);
                //所属部门id
                hrmJobtitles.setJobdepartmentId(departId);
                //岗位状态
                hrmJobtitles.setJobtitlesStatus(strJobtitlesStatus);
                //岗位部门编码
                hrmJobtitles.setDepartCode(strJobtitlesDepartCode);
                //岗位序列
                hrmJobtitles.setGwxl(strGwxl);
                //******4.数据的插入或更新开始执行,操作岗位表
                //根据岗位编码获取岗位id，岗位id为空字符串则执行插入操作；岗位id有值的话，则执行更新操作。
                String jobIdStr = sosDao.getIdByCode("hrmjobtitles", strJobtitlesCode);
                String strSqls="select id from hrmjobtitles where jobtitlecode='"+strJobtitlesCode+"'";
                log.info("根据岗位编码获取岗位id Sql:"+strSqls+";查询结果："+strSqls);
                if ("".equals(jobIdStr)) {
                    boolean insertJobStatus = sosDao.insertHrmJobTitle(hrmJobtitles);
                    if (!insertJobStatus) {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                        writeBackDataJson.put("ifmsg", "岗位编码为" + hrmJobtitles.getJobtitleCode() + ",插入的时候，插入失败.");
                        log.error("岗位编码为" + hrmJobtitles.getJobtitleCode() + ",插入的时候，插入失败.");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("岗位编码为" + hrmJobtitles.getJobtitleCode() + "插入失败.");
                    } else {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                        writeBackDataJson.put("ifmsg", "岗位同步成功");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("岗位同步成功");
                    }
                } else {
                    hrmJobtitles.setId(jobIdStr);
                    boolean updateJobStatus = sosDao.updateHrmJobTitleTable(hrmJobtitles);
                    if (!updateJobStatus) {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                        writeBackDataJson.put("ifmsg", "岗位编码为" + hrmJobtitles.getJobtitleCode() + ",更新岗位数据失败.");
                        log.error("岗位编码为" + hrmJobtitles.getJobtitleCode() + ",更新岗位数据失败.");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("岗位编码为" + hrmJobtitles.getJobtitleCode() + "更新失败.");
                    } else {
                        //回写数据
                        writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                        writeBackDataJson.put("ifmsg", "岗位同步成功");
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("岗位同步成功");
                    }
                }
                //回写数据
                writeBackDataList.add(writeBackDataJson);
                //日志插入
//                sosDao.insertSyncLog(syncLog);
            }


            //日志插入完成后,开启线程授权
            //传入授权类的sql
            //模块id
            log.info("开始授权--");
            int modeId = SyncOrgStrucDaoImpl.getModeIdByTableName("uf_sjtbrz");
            log.info("模块id:"+modeId);
            String  sql="select id from uf_sjtbrz where syncdate='"+CommonToSapUtil.getCurDate()+"' and synctype='"+CommonConstant.SYNC_TYPE_JOB+"'";
            log.info("授权sql:"+sql);
            ModeDataShareByThreads modeDataShareByThread = new ModeDataShareByThreads();
            modeDataShareByThread.setModeid(modeId);
            modeDataShareByThread.setSql(sql);
            new Thread(modeDataShareByThread).start();
            log.info("结束授权--");
            //数据回写
            this.writeBackSyncInfo(log,CommonConstant.SYNC_TYPE_JOB, writeBackDataList, isall);
        } else {
            log.info("岗位同步==>syncJobtitlesInfo():本次没有可同步的岗位数据。");
        }
        //清除岗位缓存
        syncUtil.clearCache(2);
        //**同步结束
    }


    /**
     * 人员同步
     */
    @Override
    public void syncResourceInfo(Logger log,String isall) {
        log.info("开始同步人员---");
        //同步日志记录
//        SyncLog syncLog = new SyncLog();
        HrmResource hrmResource = new HrmResource();
        SyncOrgStrucDao sosDao = new SyncOrgStrucDaoImpl();
        //人员信息封装类
        GetUserMessageUtil getUserMessageUtil = new GetUserMessageUtil();
        //数据库操作类
        RecordSet rs = new RecordSet();

        //同步工具类
        SyncUtil syncUtil = new SyncUtil();
        //获取同步人员接口的url
        String strSyncResourceInfoUrl = Util.null2String(this.getPropValue("sapMess", "syncResourceUrl"));
        log.info("人员同步==" + strSyncResourceInfoUrl);
        //查询人员xml
        String strRequestXml = syncUtil.getOrgXml(log,"resourceInfo", null, isall);
        log.info("人员同步的xml:" + strRequestXml);
        //******1.获取要同步的人员数据
        JSONObject jsonObject=this.getSyncResourceDataInfos(log,strSyncResourceInfoUrl, strRequestXml);
        if(jsonObject!=null) {
            //主账号数据
            JSONArray resourceList = jsonObject.getJSONArray("mainJob");

            //******2.存在人员数据，则进行同步
            if (resourceList != null) {
                //回写数据list集合
                List<JSONObject> writeBackDataList = new ArrayList<JSONObject>();
                //人员返回长度
                int intUserNum = resourceList.size();
                log.info("人员返回长度:" + intUserNum);
                //******3.遍历人员数据，逐条插入或更新到OA数据库,测试一条数据
                for (int index = 0; index < intUserNum; index++) {
                    //回写数据json
                    JSONObject writeBackDataJson = new JSONObject();
                    //******3.1获取要同步的参数
                    JSONObject subComMap = JSON.parseObject(resourceList.get(index).toString());
                    //人员信息封装
                    hrmResource = getUserMessageUtil.getHrmResource(subComMap, rs, sosDao);
                    log.info("转换后的人员信息数据：" + hrmResource.toString());
                    //同步日志数据初始化
//                    syncLog.setSyncType(CommonConstant.SYNC_TYPE_RESOURCE);
//                    syncLog.setSyncDate(CommonToSapUtil.getCurDate());
//                    syncLog.setSyncTime(CommonToSapUtil.getCurTime());
//                    syncLog.setSyncCode(hrmResource.getWorkCode());
//                    syncLog.setSyncName(hrmResource.getLastName());

                    //回写数据
                    writeBackDataJson.put("workcode", hrmResource.getWorkCode());

                    //******3.2判断一些必须字段是否有值，来决定是否可同步该条记录
                    //判断人员编码是否为空
                    if ("".equals(hrmResource.getLastName())) {
                        log.info("人员姓名不能为空，同步失败！");
                        //日志插入
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("人员姓名为空");
//                        sosDao.insertSyncLog(syncLog);
                        continue;
                    }

//                //上级领导唯一性判断
//                String managerId = sosDao.getIdByCode("hrmresource", managerCode);
//                // String hrmManagerId = sosDao.getIdByCode("hrmresourcebyid", managerId);
//                String managerStr = sosDao.getManagerIdAndStr(managerId);

                    //******4.数据的插入或更新开始执行
                    //根据人员唯一标识获取人员id，人员id为空字符串则执行插入操作；人员id有值的话，则执行更新操作。
                    int userId = Util.getIntValue(sosDao.getIdByCode("hrmresource", hrmResource.getWorkCode()), 0);
                    if (userId == 0) {
                        userId = sosDao.getHrmMaxid();
                        hrmResource.setId(userId);
                        //**在插入前判断license
                        if (!"".equals(hrmResource.getStrLoginid())) {
                            LN l = new LN();
                            int lnum = l.CkHrmnum();
                            log.info("判断license的依据:" + lnum + ";当前用户id:" + userId);
                            if (lnum > 0) {
                                //说明license达到最大值,此时退出当前循环
                                log.info("license达到最大值");
                                continue;
                            }
                        }
                        //控制license结束

                        boolean insertResourceStatus = sosDao.insertHrmResource(hrmResource);
                        if (!insertResourceStatus) {
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                            writeBackDataJson.put("ifmsg", "人员同步成功" + hrmResource.getWorkCode() + ",插入失败");
                            log.error("人员唯一标识为" + hrmResource.getWorkCode() + ",插入的时候，插入失败.");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                            syncLog.setSyncInfoDesc("人员唯一标识为" + hrmResource.getWorkCode() + "插入失败.");

                        } else {
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                            writeBackDataJson.put("ifmsg", "人员同步成功");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                            syncLog.setSyncInfoDesc("人员同步成功");

                        }
                    } else {
                        hrmResource.setId(userId);
                        //**在插入前判断license
                        if (!"".equals(hrmResource.getStrLoginid())) {
                            LN l = new LN();
                            int lnum = l.CkHrmnum();
                            log.info("更新人员判断license的依据:" + lnum);
                            if (lnum > 0) {
                                //说明license达到最大值,此时退出当前循环
                                log.info("license达到最大值");
                                continue;
                            }
                        }
                        boolean updateResourceStatus = sosDao.updateHrmResource(hrmResource);
                        if (!updateResourceStatus) {
                            //回写数据
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_DEFULT);
                            writeBackDataJson.put("ifmsg", "人员唯一标识为" + hrmResource.getWorkCode() + ",更新人员数据失败.");
                            log.error("人员唯一标识为" + hrmResource.getWorkCode() + ",更新人员数据失败.");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                            syncLog.setSyncInfoDesc("人员唯一标识为" + hrmResource.getWorkCode() + ",更新人员数据失败.");
                        } else {
                            //回写数据
                            writeBackDataJson.put("ifflg", CommonConstant.SYNC_BACk_SUCCESS);
                            writeBackDataJson.put("ifmsg", "人员同步成功");
//                            syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                            syncLog.setSyncInfoDesc("人员同步成功");
                        }
                    }
                    //回写数据
                    writeBackDataList.add(writeBackDataJson);

                    //日志插入
//                    sosDao.insertSyncLog(syncLog);
                }

                //主账号信息处理完成后,处理次账号的数据
                JSONArray jsonArraySecond = jsonObject.getJSONArray("secondJob");
                log.info("返回的次岗位信息:" + jsonArraySecond.toString());
                this.dealSecond(log,jsonArraySecond);

                //日志插入完成后,开启线程授权
                //传入授权类的sql
                //模块id
                log.info("开始授权--");
                int modeId = SyncOrgStrucDaoImpl.getModeIdByTableName("uf_sjtbrz");
                log.info("模块id:" + modeId);
                String sql = "select id from uf_sjtbrz where syncdate='" + CommonToSapUtil.getCurDate() + "' and synctype='" + CommonConstant.SYNC_TYPE_RESOURCE + "'";
                log.info("授权sql:" + sql);
                ModeDataShareByThreads modeDataShareByThread = new ModeDataShareByThreads();
                modeDataShareByThread.setModeid(modeId);
                modeDataShareByThread.setSql(sql);
                new Thread(modeDataShareByThread).start();
                log.info("结束授权--");

                //数据回写
                this.writeBackSyncInfo(log,CommonConstant.SYNC_TYPE_RESOURCE, writeBackDataList, isall);
            } else {
                log.info("人员同步==>syncResourceInfo():本次没有可同步的人员数据。");

            }
        }else{
            log.info("人员同步==>syncResourceInfo():jsonObject为null,本次没有可同步的人员数据。");
        }

        //人员清除缓存
        syncUtil.clearCache(3);

    }


}
